/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-3-4
 *
 */
public class InstanceSpringProvider implements InstanceProvider {

   private static ApplicationContext applicationContext;
   
   public InstanceSpringProvider(String[] locations){
	   applicationContext = new ClassPathXmlApplicationContext(locations);
   }
 
   public InstanceSpringProvider(ApplicationContext context){
	   applicationContext = context;
   }
 
   public InstanceSpringProvider(Class<?>[] annotatedClasses){
    	applicationContext = new AnnotationConfigApplicationContext(annotatedClasses);
   }

	/* (non-Javadoc)
	 * @see com.foreveross.infra.factory.InstanceProvider#getInstance(java.lang.Class)
	 */
	public <T> T getInstance(Class<T> beanClass) {
		String[] beanNames = applicationContext.getBeanNamesForType(beanClass);
		if (beanNames.length == 0) {
			return null;
		}
		return (T)applicationContext.getBean(beanNames[0]);
	}

	/* (non-Javadoc)
	 * @see com.foreveross.infra.factory.InstanceProvider#getInstance(java.lang.Class, java.lang.String)
	 */
	public <T> T getInstance(Class<T> beanClass, String beanName) {
		return applicationContext.getBean(beanName, beanClass);
	}

	/* (non-Javadoc)
	 * @see com.foreveross.infra.factory.InstanceProvider#getInstance(java.lang.String)
	 */
	public <T> T getInstance(String beanName) {
		return (T)applicationContext.getBean(beanName);
	}

}
